package mwa.cs.rc.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mwa.cs.dao.ArDAO;
import mwa.cs.dao.BackTimeDAO;
import mwa.cs.dao.RcTransDDAO;
import mwa.cs.dao.RcTransMDAO;
import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.database.Database;
import mwa.cs.model.Ar;
import mwa.cs.model.BackTime;
import mwa.cs.model.RcTransD;
import mwa.cs.model.RcTransM;
import mwa.cs.util.JDate;





import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

/**
 * Servlet implementation class CS51002Srvl
 */
public class CS51002Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private int vnSiteId;
	private int vnUserId;
	private String vaUrlAddress = "";
	private String vaAgentBrowser = "";
	
	private Database db;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public CS51002Srvl() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
		vaUrlAddress = request.getParameter("url_address");
		vaAgentBrowser = request.getParameter("agent_browser");
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		String vaProcessType  = "";
		
		try  { 
			vaProcessType =   request.getParameter("process_type");
			
			if(vaProcessType.equals("getDataTable")){
				getDataTable(request,response);
			} else if(vaProcessType.equals("searchData")){ 
				 getDataTable(request,response);
			} else if(vaProcessType.equals("recriptBill")){ 
				 recriptBill(request ,response);
			}
		} 
		catch (NullPointerException ex) { 
		}
		catch (Exception ex){					
		}
	}
	
	/** 
	 * @athor Ceo Freealife
	 * @desc  this module recript by group
	 * @param request
	 * @param response
	 */
	private void recriptBill(HttpServletRequest request,
			HttpServletResponse response) {
		
		boolean act = false;
		
		try {
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8"); 
			response.setContentType("text/JSON");
			
			this.db  = new Database();
			
			int  vnSiteId = 0;
			int  vnUserId = 0;
			int  pnRouted = 0;
			int  pnZoneId = 0;
			String vaMonth  = "";
			String vaYear  = "";
			
			if (request.getParameter("zoneId") != null) {
				pnZoneId = Integer.parseInt(request.getParameter("zoneId").trim());
			} else {
				pnZoneId = -1;
			}
			if (request.getParameter("routeId") != null) {
				pnRouted = Integer.parseInt(request.getParameter("routeId").trim());
			} else {
				pnRouted = -1;
			}
			if (request.getParameter("month") != null) {
				vaMonth = request.getParameter("month").trim();
			} else {
				vaMonth = "" + -1;
			}
			
			if (request.getParameter("year") != null) {
				vaYear = request.getParameter("year").trim();
			} else {
				vaYear = "" + -1;
			}
			
			vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
			vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
			
			try  {
				
			String[] paItems = request.getParameterValues("billNo[]");
			ArDAO voArDAO = new ArDAO(db);
			
			// Check Back Time 
			String vaReceiveTimeToDB = JDate.getTime();
			String vaReceiveDateToDB = JDate.checkBackTimeDate(vnSiteId);	
			
			for (String vaItem : paItems) {

				if (!vaItem.equals("")) {
				
					Map<String, Object> voMapItem = null;
					try  { 
						voMapItem = voArDAO.findAR(vnSiteId,pnZoneId, pnRouted, vaMonth, vaYear, vaItem);
					}catch(Exception ex){ 
					}
					
					if(voMapItem != null){
						Ar voArModel = new Ar();
						
						try { 
							
						voArModel.setVnSiteId(vnSiteId);
						voArModel.setVnZoneId(pnZoneId);
						voArModel.setVnRouteId(pnRouted);
						voArModel.setVaPeriodMonth(vaMonth);
						voArModel.setVaPeriodYear(vaYear);
						voArModel.setVaBillNumber(vaItem);
						voArModel.setVnReceiveEmployee(vnUserId);
						voArModel.setVnUpdateUserId(vnUserId);
	
						voArModel.setVaPName(voMapItem.get("PNAME") == null ? "": voMapItem.get("PNAME").toString());
						voArModel.setVaFName(voMapItem.get("FNAME") == null ? "": voMapItem.get("FNAME").toString());
						voArModel.setVaLName(voMapItem.get("LNAME") == null ? "": voMapItem.get("LNAME").toString());
						voArModel.setVaAddress(voMapItem.get("ADDRESS") == null ? "" : voMapItem.get("ADDRESS").toString());
	
						voArModel.setVnTotalAmount(Double.parseDouble(voMapItem.get("TOTAL_AMOUNT") == null ? "0.0" : voMapItem.get("TOTAL_AMOUNT").toString()));
						voArModel.setVnVatAmount(Double.parseDouble(voMapItem.get("VAT_AMOUNT") == null ? "0.0" : voMapItem.get("VAT_AMOUNT").toString()));
						voArModel.setVnWaterCharge(Double.parseDouble(voMapItem.get("WATER_CHARGE") == null ? "0.0" : voMapItem.get("WATER_CHARGE").toString()));
						voArModel.setVnWasteWaterCharge(Double.parseDouble(voMapItem.get("WASTEWATER_CHARGE") == null ? "0.0" : voMapItem.get("WASTEWATER_CHARGE").toString()));
						voArModel.setVnWaterFee(Double.parseDouble(voMapItem.get("WATER_FEE") == null ? "0.0" : voMapItem.get("WATER_FEE").toString()));
						voArModel.setVnOtherCharge(Double.parseDouble(voMapItem.get("OTHER_CHARGE") == null ? "0.0" : voMapItem.get("OTHER_CHARGE").toString()));
						voArModel.setVnGarbageCharge(Double.parseDouble(voMapItem.get("GARBAGE_CHARGE") == null ? "0.0" : voMapItem.get("GARBAGE_CHARGE").toString()));
						voArModel.setVnSerialNumber(Integer.parseInt(voMapItem.get("SERIAL_NUMBER") == null ? "0" : voMapItem.get("SERIAL_NUMBER").toString()));
						voArModel.setVaAccount(voMapItem.get("ACCOUNT") == null ? "": voMapItem.get("ACCOUNT").toString());
						voArModel.setVaReceiveDate(vaReceiveDateToDB);
						voArModel.setVaReceiveTime(vaReceiveTimeToDB);
						voArModel.setVaUpdateDate(JDate.getDate());
						voArModel.setVaUpdateTime(JDate.getTime());
						voArModel.setVnSeq(Integer.parseInt(voMapItem.get("SEQ") == null ? "0": voMapItem.get("SEQ").toString()));
	
						}catch (Exception ex){				
						}
						try {
							if (insertRCTransM(this.db, voArModel, request)) {
								if (insertRCTransD(this.db, voArModel)) {
									if (voArDAO.updateRecriveBillNumber(voArModel)) {
										act = true;
									}
								}
							}
						} catch (Exception ex){ 
							SMErrorLogDAO.getInstance().addLog(0, "CS51002", JDate.getDate(), JDate.getTime(),vnUserId, "CS51002Srvl", ex.getMessage(),vaUrlAddress, vaAgentBrowser);					
						}
					}
				}
			}
			PrintWriter voOut  = response.getWriter();
			if(act){
				voOut.print("success");
			} else  { 
				voOut.print("fail");
			}
			}catch (Exception ex){				
			}
		} catch (NullPointerException ex) {			
		} catch (Exception ex){				
			this.db.rollback();
		} finally {
			db.close();
		}
	}

	private boolean insertRCTransD(Database db, Ar arModel) {
		boolean vaAct  = false;
		try{ 
			

			RcTransDDAO voRcTransDDAO = new RcTransDDAO(db);
			RcTransD vaRcTransD = new RcTransD();
			
			vaRcTransD.setVnSiteId(arModel.getVnSiteId());
			vaRcTransD.setVnSerialNumber(arModel.getVnSerialNumber());
			vaRcTransD.setVnSeqNumber(arModel.getVnSeq());
			vaRcTransD.setVnBillAmount(arModel.getVnBillAmount());
			vaRcTransD.setVaBillNumber(arModel.getVaBillNumber());
			vaRcTransD.setVaReceiveCode("21");
			vaRcTransD.setVnWaterCharge(arModel.getVnWaterCharge());
			vaRcTransD.setVnWaterFee(arModel.getVnWaterFee());
			vaRcTransD.setVnVatAmount(arModel.getVnVatAmount());
			vaRcTransD.setVnWasteWaterCharge(arModel.getVnWasteWaterCharge());
			vaRcTransD.setVnGarbageCharge(arModel.getVnGarbageCharge());
			vaRcTransD.setVnOtherCharge(arModel.getVnOtherCharge());
			vaRcTransD.setVnBillAmount(arModel.getVnTotalAmount());
			vaRcTransD.setVnInsertUserId(arModel.getVnInsertUserId());
			vaRcTransD.setVaInsertDate(JDate.getDate());
			vaRcTransD.setVaInsertTime(JDate.getTime());
			
			 voRcTransDDAO.insertRcTransD(vaRcTransD);
			vaAct  = true;
		}catch(Exception ex){
			SMErrorLogDAO.getInstance().addLog(0, "CS51002", JDate.getDate(), JDate.getTime(),vnUserId, "CS51002Srvl", ex.getMessage(),vaUrlAddress, vaAgentBrowser);					
			vaAct = false;
		}
		return vaAct;
	}

	private boolean insertRCTransM(Database db, Ar poArModel, HttpServletRequest request) throws SQLException {
		// Check Back Time 
		int vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		BackTimeDAO voBackTimeDAO = new BackTimeDAO(db);
		String vaReceiveDateToDB = JDate.getDate();	
		String vaReceiveTimeToDB = JDate.getTime();
		try {
			BackTime voBackTime = voBackTimeDAO.getExpireAndBackTimeDate(vnSiteId); 
			String vaExpireDate = voBackTime.getVaExpireDate();
			String vaBackTimeDate = voBackTime.getVaBackTimeDate();
			Locale.setDefault(new Locale("th","TH"));
			DateFormat voDateFormat = new SimpleDateFormat("yyyyMMdd");
			Date voExprieDate = voDateFormat.parse(vaExpireDate);
			String vaCurrent = voDateFormat.format(new Date());
			Date voCurrent = voDateFormat.parse(vaCurrent);
			if ( voExprieDate.after(voCurrent) || voExprieDate.equals(voCurrent) ){
				// "Is Not Expire..."
				vaReceiveDateToDB = vaBackTimeDate;
			} else {
				// "Is Expire..."
//				vaReceiveDateToDB = JDate.getDate();
			}
		} catch (Exception e) {				
			System.out.println(e.getMessage());
		}
		boolean vbAct  = false;
		try {
			RcTransMDAO voRcTransMDAO = new RcTransMDAO(db);
			RcTransM rcTransM = new RcTransM();
			rcTransM.setVnSiteId(poArModel.getVnSiteId());
			rcTransM.setVnSerialNumber(poArModel.getVnSerialNumber());
			rcTransM.setVaAccount(poArModel.getVaAccount());
			rcTransM.setVaPayerName(poArModel.getVaPName() + " " + poArModel.getVaFName() + " " + poArModel.getVaLName());
			rcTransM.setVaPayerAddress(poArModel.getVaAddress());
			rcTransM.setVaAccount(poArModel.getVaAccount());
			rcTransM.setVaReceiveDate(JDate.getDate());
			rcTransM.setVaReceiveTime(JDate.getTime());
			rcTransM.setVnReceiveEmployee(poArModel.getVnUpdateUserId());
			rcTransM.setVnNetAmount(poArModel.getVnTotalAmount() - poArModel.getVnVatAmount());
			rcTransM.setVnVatAmount(poArModel.getVnVatAmount());
			rcTransM.setVnGrossAmount(poArModel.getVnTotalAmount());
			rcTransM.setVnInsertUserId(poArModel.getVnUpdateUserId());		
			rcTransM.setVaInsertDate(vaReceiveDateToDB);
			rcTransM.setVaInsertTime(vaReceiveTimeToDB);
			voRcTransMDAO.insertRcTransM(rcTransM);
			vbAct = true;
		} catch(Exception ex){
			SMErrorLogDAO.getInstance().addLog(0, "CS51002", JDate.getDate(), JDate.getTime(),vnUserId, "CS51002Srvl", ex.getMessage(),vaUrlAddress, vaAgentBrowser);
			vbAct = false;
		}
		return vbAct;
	}

	public void getDataTable(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		
		int  vnSiteId = 0;
		int  vnUserId = 0;
		int  pnRouted = 0;
		int  pnZoneId = 0;
		int  vnDataSize = 0;
		String vaMonth  = "";
		String vaYear  = "";
		int vnStart = 0; 
		int vnAmount = 0;
		int vnEnd = 0;
		
		try{
			if(request.getParameter("iDisplayStart") != null){
				vnStart = Integer.parseInt(request.getParameter("iDisplayStart")); 	 // 0
			} else  {
				vnStart = 0;
			}
			if(request.getParameter("iDisplayLength") != null){
				vnAmount = Integer.parseInt(request.getParameter("iDisplayLength")); // 10
			}else{
				vnAmount = 10;
			}
			vnEnd = vnStart + vnAmount;
						
			if (request.getParameter("sSearch_0") != null) {
				pnZoneId = Integer.parseInt(request.getParameter("sSearch_0").trim());
			} else {
				pnZoneId = -1;
			}
			if (request.getParameter("sSearch_1") != null) {
				pnRouted = Integer.parseInt(request.getParameter("sSearch_1").trim());
			} else {
				pnRouted = -1;
			}
			if (request.getParameter("sSearch_2") != null) {
				vaMonth = request.getParameter("sSearch_2").trim();
			} else {
				vaMonth = "" + -1;
			}
			if (request.getParameter("sSearch_3") != null) {
				vaYear = request.getParameter("sSearch_3").trim();
			} else {
				vaYear = "" + -1;
			}
			
			
		} catch (NullPointerException ex) {
			pnZoneId  = -1;
			pnRouted = -1;
			vaMonth = "" + -1;
			vaYear  = "" + -1;
		} catch (Exception ex) {
		}

		vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());

		try {

			JSONObject voObject = new JSONObject();
			JSONArray voRow = new JSONArray();
			JDate voJDate = new JDate();
			PrintWriter voOut = response.getWriter();
			this.db = new Database();
			ArDAO voArDAO = new ArDAO(db);
			List<Map<String, Object>> voListFindAll;

			// listFindAll = daoArDAO.findArBySite(vnSiteId);
			if (pnZoneId == 0 && pnRouted == 0 && vaMonth.equals("")
					&& vaYear.equals("")) {
//				listFindAll = daoArDAO.findArByCondition(vnSiteId, pnZoneId,
//						pnRouted, month, year);
				voListFindAll = new ArrayList<Map<String,Object>>();
				vnDataSize = 0;
			} else {
				Map<String, Object> voItems = voArDAO.findArCountByCondition(
						vnSiteId, pnZoneId, pnRouted, vaMonth, vaYear).get(0);
				vnDataSize = Integer.parseInt(voItems.get("AR_COUNT").toString());
				voListFindAll = voArDAO.findArByConditionAndStart(vnSiteId,
						pnZoneId, pnRouted, vaMonth, vaYear, vnStart, vnEnd);
			}

			int vnIndex = vnStart;
			for (int i = 0; i < voListFindAll.size(); i++) {
				Map<String, Object> voMapItem = (Map<String, Object>) voListFindAll.get(i);
				JSONArray voColumn = new JSONArray();
				voColumn.add("");
				voColumn.add(++vnIndex);
				voColumn.add(voMapItem.get("BILL_NUMBER")== null ? ""  : voMapItem.get("BILL_NUMBER").toString());
				voColumn.add(voMapItem.get("ACCOUNT_RECEIVABLE_DATE") == null ? ""  :  JDate.showDate(voMapItem.get("ACCOUNT_RECEIVABLE_DATE").toString()));
				
				if(voMapItem.get("PNAME") == null && voMapItem.get("FNAME") == null){
					voColumn.add(voMapItem.get("PNAME").toString() + " " + voMapItem.get("FNAME").toString() + " " + voMapItem.get("LNAME").toString());
				}else{ 
					voColumn.add(voMapItem.get("PNAME").toString() + " " + voMapItem.get("FNAME").toString() + " " + voMapItem.get("LNAME").toString());
				}
				
				voColumn.add(voMapItem.get("WATER_CHARGE") == null ? "0" : voMapItem.get("WATER_CHARGE").toString());
				voColumn.add(voMapItem.get("WATER_FEE") == null ? "0" : voMapItem.get("WATER_FEE").toString());
				voColumn.add(voMapItem.get("VAT_AMOUNT")== null ? "0.00" : voMapItem.get("VAT_AMOUNT").toString());
				voColumn.add(voMapItem.get("BILL_AMOUNT") == null ? "0.00" : voMapItem.get("BILL_AMOUNT"));
				voColumn.add(voMapItem.get("TOTAL_AMOUNT") == null ? "0.00" : voMapItem.get("TOTAL_AMOUNT"));
				voColumn.add(voMapItem.get("RECEIVE_DATE") == null ? "" : voMapItem.get("RECEIVE_DATE").toString());
				voRow.add(voColumn);
			}
			voObject.put("iTotalRecords", vnDataSize);
			voObject.put("iTotalDisplayRecords", vnDataSize);
			voObject.put("aaData", voRow);

			//System.out.println(" >> " + voObject.toJSONString());

			voOut.print(voObject.toJSONString());

		} catch (Exception ex) {
		} finally{
			db.close();
		}
			
	}
}